package edu.indiana.d2i.vmm.job;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import edu.indiana.d2i.vmm.job.rsl.JobDescriptionType;
import edu.indiana.d2i.vmm.job.rsl.JobTypeEnumeration;
import edu.indiana.d2i.vmm.job.rsl.NameValuePairType;
import edu.indiana.d2i.vmm.job.rsl.ObjectFactory;

public class SigiriHTRCJobDescription {
	private static JobDescriptionType description = new JobDescriptionType();
	
	private SigiriHTRCJobDescription(Builder builder) {}
	
	public static class Builder {
		public Builder setExecutable(String exeName, String exePath) {
			description.setExecutable(exeName);
			return addEnvArg(SigiriHTRCConstants.EXECUTABLE_PATH, exePath);
		}
		
		public Builder setUserID(String userID) {
			description.setLocalUserId(userID);
			return this;
		}
		
		public Builder addUserArgsInOrder(String arg) {
			description.getArgument().add(arg);
			return this;
		}
		
		public Builder setImageInfo(String type, int num) {
			return addEnvArg(SigiriHTRCConstants.IMAGE_TYPE, type).
				addEnvArg(SigiriHTRCConstants.INSTANCE_NUMBER, String.valueOf(num));
		} 
		
		public Builder setSoftwareFramework(String software) {
			return addEnvArg(SigiriHTRCConstants.SOFTWARE_FRAMEWORK, software);
		} 
		
		public Builder setOutputFile(String outputFile) {
			return addEnvArg(SigiriHTRCConstants.OUTPUT_FILE, outputFile);
		}
		
		public Builder setJobType(JobTypeEnumeration jobType) {
			description.setJobType(jobType);
			return this;
		}
		
		public Builder setPropertyFile(String propName, String propPath) {
			return addEnvArg(SigiriHTRCConstants.PROPERTY_NAME, propName).
				addEnvArg(SigiriHTRCConstants.PROPERTY_PATH, propPath);
		}
		
		private Builder addEnvArg(String name, String value) {
			NameValuePairType namevalue = new NameValuePairType();
			namevalue.setName(name);namevalue.setValue(value);
			description.getEnvironment().add(namevalue);
			return this;
		}
		
		public SigiriHTRCJobDescription build() {
			return new SigiriHTRCJobDescription(this);
		}
	}

	public String toXMLString() throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance("edu.indiana.d2i.vmm.job.rsl");
		Marshaller marshaller = jaxbContext.createMarshaller();
		ObjectFactory factory = new ObjectFactory();
		JAXBElement<JobDescriptionType> createJob = factory.createJob(description);
		OutputStream out = new ByteArrayOutputStream();
		marshaller.marshal(createJob, out);
		return out.toString();
	}
}
